import Vue from "vue";
import {
  login,
  getInfo,
  logout,
  getAllConfigData,
  enterpriseWeChatLogin,
  enterpriseDingtalkLogin,
  getListProject,
  getAccountPower,
  getTreeProject,
} from "@/services/user.js";
import { postAxiosRequest } from "@/services/common";
import {
  ACCESS_TOKEN,
  PHONE_NUMBER,
  BLACK_TOKEN,
} from "@/store/mutation-types";
import { welcome, _getUUID, flatTreeData } from "@/utils/util";
import { setDocumentTitle, setDocumentIco } from "@/utils/domUtil";
import { delCookie, setCookie } from "@/utils/TopVUI.js";
const user = {
  state: {
    token: "",
    name: "",
    welcome: "",
    avatar: "",
    roles: [],
    info: {},
    configData: [],
    phoneNumber: "",
    dataPermissions: [],
    //引擎系统【初始化】完成标识
    RESystemReady: false,
    //引擎系统【创建】完成、公共资源加载完成
    RESystemRenderReady: false,
    ///////////////////////////////////
    //【黑洞】黑洞资源预加载完成标识
    BLACKhOLE_ASSETS_PREFETCH: false,
    //【黑洞】系统初始化完成
    BLACKhOLE_RE_SYSTEM_READY: false,
    //【黑洞】系统引擎创建完成
    BLACKhOLE_RE_SYSTEM_CREATED: false,
    //【黑洞】卸载标识
    BLACKhOLE_RELEASE_ENGINE: false,
    //全局项目
    CURRENT_PROJECT_CODE: "",
    //选择项目
    CURRENT_PROJECT: {},
    //全局项目集合
    TENANT_DATA: [],
    ACTIVE_MENU: "",
    //账号权限
    USER_ACCOUNT: "",
  },
  mutations: {
    //【通用级方法】动态添加state
    SET_STORE_STATE: (state, data = {}) => {
      if (Object.prototype.toString.call(data) !== "[object Object]") {
        console.error(`${data} is not an Object type`);
      } else {
        Object.keys(data).forEach((key) => {
          if (state.hasOwnProperty(key)) {
            Object.assign(state, {
              [key]: data[key],
            });
          } else {
            Vue.set(state, key, data[key]);
          }
        });
      }
    },
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_NAME: (state, name) => {
      state.name = name;
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_INFO: (state, info) => {
      state.info = info;
    },
    SET_CONFIG_DATA: (state, configData) => {
      state.configData = configData;
    },
    SET_PHONE_NUMBER: (state, phoneNumber) => {
      state.phoneNumber = phoneNumber;
    },
    SET_DATA_PERMISSIONS: (state, dataPermissions) => {
      state.dataPermissions = dataPermissions;
    },
  },
  actions: {
    //【通用级方法】添加state
    setStoreState({ commit }, data) {
      if (Object.prototype.toString.call(data) !== "[object Object]") {
        console.error(`${data} is not an Object type`);
        return;
      }
      commit("SET_STORE_STATE", data);
    },

    //查询账号权限
    getAccountData({ commit }) {
      return new Promise((resolve, reject) => {
        getAccountPower()
          .then((res) => {
            commit("SET_STORE_STATE", { USER_ACCOUNT: res?.data ?? "" });
            resolve(res);
          })
          .catch((_) => {
            commit("SET_STORE_STATE", { USER_ACCOUNT: "" });
            reject(_);
          });
      });
    },

    //查询用户项目列表
    getListProjectData({ commit }) {
      return new Promise((resolve, reject) => {
        getListProject({ page: 1, pageSize: 999, proName: "", proId: "" })
          .then((res) => {
            let { data } = res;
            let source = data.rows || [];
            resolve(source);
          })
          .catch((_) => {
            reject([]);
          });
      });
    },
    //查询用户项目树
    getTreeProjectData({ commit }) {
      return new Promise((resolve, reject) => {
        getTreeProject()
          .then((res) => {
            let source = res?.data || [];
            commit("SET_STORE_STATE", { TENANT_DATA: source });
            // let flatData = flatTreeData(source, "children");
            let currentCode = localStorage.getItem("CURRENT_PROJECT_CODE");
            let currentData = JSON.parse(
              localStorage.getItem("CURRENT_PROJECT" ?? "{}")
            );
            if (currentCode) {
              commit("SET_STORE_STATE", { CURRENT_PROJECT: currentData });
              commit("SET_STORE_STATE", { CURRENT_PROJECT_CODE: currentCode });
              localStorage.setItem("CURRENT_PROJECT_CODE", currentCode);
              localStorage.setItem(
                "CURRENT_PROJECT",
                JSON.stringify(currentData)
              );
            } else {
              commit("SET_STORE_STATE", { CURRENT_PROJECT: {} });
              commit("SET_STORE_STATE", { CURRENT_PROJECT_CODE: "" });
              localStorage.setItem("CURRENT_PROJECT", JSON.stringify({}));
              localStorage.setItem("CURRENT_PROJECT_CODE", "");
            }
            resolve(source);
          })
          .catch((_) => {
            commit("SET_STORE_STATE", { TENANT_DATA: [] });
            commit("SET_STORE_STATE", { CURRENT_PROJECT: {} });
            commit("SET_STORE_STATE", { CURRENT_PROJECT_CODE: "" });
            reject([]);
          });
      });
    },

    // 登录
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo)
          .then((response) => {
            const result = response;
            if (result.statusCode === 200) {
              const token = result.message.substring(7);
              const blackToken = result.blackToken;
              Vue.ls.set(ACCESS_TOKEN, token);
              commit("SET_TOKEN", token);
              setCookie("token", token);
              Vue.ls.set(BLACK_TOKEN, blackToken);
              setCookie("blackToken", blackToken);
              resolve(result);
            } else {
              reject(result);
            }
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    // 设置token
    SetToken({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        if (userInfo) {
          Vue.ls.set(ACCESS_TOKEN, userInfo);
          commit("SET_TOKEN", userInfo);
          resolve();
        } else {
          reject(result);
        }
      });
    },
    // 获取页面按钮授权数据
    getUserInForAndButtonPermissions({ commit }, token) {
      return new Promise((resolve, reject) => {
        let url = "";
        let ajaxData = { type: "dev" };
        if (process.env.VUE_APP_TYPE === "mis_vue") {
          url = "/system/getUserInForAndButtonPermissions";
        } else {
          url = "/system/menu/getAllVueButtonData";
          if (process.env.NODE_ENV === "production") {
            //判断取用那个菜单，主要针对于topjui版本的流程和表单
            ajaxData = { type: "production" };
          }
        }
        getInfo(url, ajaxData)
          .then((response) => {
            let { data } = response;
            let isStr =
              Object.prototype.toString.call(data) === "[object String]";
            if (response.statusCode === 200) {
              // && response.data.role.permissions.length > 0
              if (response.data.role) {
                const role = response.data.role;
                role.permissions = response.data.role.permissions;
                role.permissions.map((per) => {
                  if (
                    per.actionEntitySet != null &&
                    per.actionEntitySet.length > 0
                  ) {
                    const action = per.actionEntitySet.map((action) => {
                      return action.action;
                    });
                    per.actionList = action;
                  }
                });
                role.permissionList = role.permissions.map((permission) => {
                  return permission.permissionId;
                });
                commit("SET_ROLES", response.data.role);
              }
              resolve(response.data);
            } else {
              reject({ message: response.message });
            }
          })
          .catch((error) => {
            reject(error);
          });
        postAxiosRequest("/mdata/user/getCurrentUserInfor").then((res) => {
          commit("SET_NAME", res.userName);
          commit("SET_AVATAR", res.userHeadPortrait);
          commit("SET_INFO", res);
          localStorage.setItem("USER_INFO", JSON.stringify(res));
        });
      });
    },
    getPermissionIdentifyingByRoleId({ commit }) {
      return new Promise((resolve, reject) => {
        let url = "/system/sysDataPermission/getPermissionIdentifyingByRoleId";
        getInfo(url)
          .then((response) => {
            if (response.statusCode === 200) {
              if (response.data && response.data.length > 0) {
                commit("SET_DATA_PERMISSIONS", response.data);
              }
              resolve(response.data);
            } else {
              reject(response);
            }
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    // 获取用户信息
    SetUserInfo({ commit }) {
      return new Promise((resolve, reject) => {
        postAxiosRequest("/mdata/user/getCurrentUserInfor")
          .then((res) => {
            commit("SET_NAME", res.userName);
            commit("SET_AVATAR", res.userHeadPortrait);
            commit("SET_INFO", res);
            localStorage.setItem("USER_INFO", JSON.stringify(res));
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    // 获取系统配置信息
    GetAllConfigData({ commit }, token) {
      return new Promise((resolve, reject) => {
        getAllConfigData(token)
          .then((response) => {
            const result = response;
            if (result.statusCode != 300) {
              if (!token) {
                let titleIndex = result.findIndex(
                  (item) => item.code === "browserTitle"
                );
                let titleValue =
                  titleIndex && titleIndex > -1
                    ? result[titleIndex].value
                    : process.env.VUE_APP_NAME;
                setDocumentTitle(titleValue);
              }
              let iconIndex = result.findIndex(
                (item) => item.code === "browserIcon"
              );
              let iconValue =
                iconIndex && iconIndex > -1 ? result[iconIndex].value : "";
              setDocumentIco(iconValue);
              commit("SET_CONFIG_DATA", result);
              resolve();
            } else {
              reject(result);
            }
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 登出
    Logout({ commit, state }) {
      return new Promise((resolve) => {
        logout(state.token)
          .then(() => {
            resolve();
          })
          .catch(() => {
            resolve();
          })
          .finally(() => {
            //清空state
            commit("SET_TOKEN", "");
            commit("SET_ROLES", []);
            commit("SET_PHONE_NUMBER", "");
            Vue.ls.remove(ACCESS_TOKEN);
            Vue.ls.remove(PHONE_NUMBER);
            delCookie("token");
            commit("SET_ROUTERS", []);
            //
            commit("SET_STORE_STATE", { TENANT_DATA: [] });
            commit("SET_STORE_STATE", { CURRENT_PROJECT: {} });
            commit("SET_STORE_STATE", { CURRENT_PROJECT_CODE: "" });
            commit("SET_STORE_STATE", { USER_ACCOUNT: "" });
            commit("SET_STORE_STATE", { ACTIVE_MENU: "" });
            //
            localStorage.clear();
            sessionStorage.clear();
          });
      });
    },

    // token过期登出
    LogoutByErrorCode({ commit, state }) {
      return new Promise((resolve) => {
        //清空state
        commit("SET_TOKEN", "");
        commit("SET_ROLES", []);
        commit("SET_PHONE_NUMBER", "");
        Vue.ls.remove(ACCESS_TOKEN);
        Vue.ls.remove(PHONE_NUMBER);
        delCookie("token");
        commit("SET_ROUTERS", []);
        //
        commit("SET_STORE_STATE", { TENANT_DATA: [] });
        commit("SET_STORE_STATE", { CURRENT_PROJECT: {} });
        commit("SET_STORE_STATE", { CURRENT_PROJECT_CODE: "" });
        commit("SET_STORE_STATE", { USER_ACCOUNT: "" });
        commit("SET_STORE_STATE", { ACTIVE_MENU: "" });
        //
        localStorage.clear();
        sessionStorage.clear();
        resolve();
      });
    },
    // 第三方登录 企业weiixn
    EnterpriseWeChatLogin({ commit }, param) {
      return new Promise((resolve, reject) => {
        enterpriseWeChatLogin(param)
          .then((response) => {
            const result = response;
            if (result.statusCode === 200) {
              const token = result.token;
              Vue.ls.set(ACCESS_TOKEN, token);
              commit("SET_TOKEN", token);
              resolve();
            } else {
              reject(result);
            }
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 第三方登录  钉钉
    EnterpriseDingtalkLogin({ commit }, param) {
      return new Promise((resolve, reject) => {
        enterpriseDingtalkLogin(param)
          .then((response) => {
            const result = response;
            if (result.statusCode === 200) {
              const token = result.token;
              Vue.ls.set(ACCESS_TOKEN, token);
              commit("SET_TOKEN", token);
              resolve();
            } else {
              reject(result);
            }
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
  },
};

export default user;
